package cn.weekimwee.firstlineofcodeforkotlin.unit10

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.View
import cn.weekimwee.firstlineofcodeforkotlin.BaseActivity
import cn.weekimwee.firstlineofcodeforkotlin.R
import cn.weekimwee.firstlineofcodeforkotlin.unit10.download.DownloadActivity
import kotlinx.android.synthetic.main.activity_unit10.*
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.startService

class Unit10Activity : BaseActivity() {

    private val updateText =1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_unit10)
        handlerButton.setOnClickListener { it.onClick() }
        startServiceButton.setOnClickListener { it.onClick() }
        startIntentServiceButton.setOnClickListener { it.onClick() }
        startDownloadButton.setOnClickListener { it.onClick()}
    }

    private fun View.onClick(){
        when(this.id){
            R.id.handlerButton -> {
                Thread({
                    handlerThis.sendMessage(Message().apply {
                        what = updateText
                    })
                }).start()
            }
            R.id.startServiceButton -> startActivity<ServiceActivity>()
            R.id.startIntentServiceButton -> startService<MyIntentService>()
            R.id.startDownloadButton -> startActivity<DownloadActivity>()
        }
    }

    private val handlerThis = @SuppressLint("HandlerLeak")
    object :Handler(){
        override fun handleMessage(msg: Message?) {
            when(msg?.what){
                updateText ->{
                    handlerButton.text = "update update"
                }
            }
        }
    }
}
